package huhx.linux.com.kotlinlearn.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

	/**
	 * 优化磁盘读写和网络请求
	 */
	public static void setStrictMode() {

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());

		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());
	}

	/**
	 * 释放ImageView里的图片，防止加载过多内存溢出
	 * 
	 * @param imageView
	 */
	@SuppressWarnings("deprecation")
	public static void releaseImageViewResouce(ImageView imageView) {

		if (imageView == null)
			return;
		Drawable drawable = imageView.getDrawable();

		imageView.setImageDrawable(null);
		imageView.setBackgroundDrawable(null);
		if (drawable != null)
			drawable.setCallback(null);
		if (drawable != null && drawable instanceof BitmapDrawable) {
			BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
			Bitmap bitmap = bitmapDrawable.getBitmap();
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
		}
		imageView = null;
	}

	private static String[] known_pipes = { "/dev/socket/qemud",
			"/dev/qemu_pipe" };

	/**
	 * 检测是否在模拟器上运行
	 * 
	 * @return
	 */
	public static boolean checkPipes() {
		for (int i = 0; i < known_pipes.length; i++) {
			String pipes = known_pipes[i];
			File qemu_socket = new File(pipes);
			if (qemu_socket.exists()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 以最省内存的方式读取本地资源的图片  
	 * 
	 * @param context
	 * @param resId
	 * @param iv
	 * @return
	 */
	public static void setImageViewBitmap(Context context, int resId,
			ImageView iv) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		Bitmap bitmap = BitmapFactory.decodeStream(is, null, opt);
		Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
		Bitmap pbitmap = iv.getDrawingCache();
		if (pbitmap != null && !pbitmap.isRecycled())
			pbitmap.recycle();
		iv.setImageDrawable(drawable);
	}

	public static void exitApp() {
		android.os.Process.killProcess(android.os.Process.myPid()); // 获取PID
		System.exit(0); // 常规java、c#的标准退出法，返回值为0代表正常退出
	}

	public static String getEdtText(EditText edt) {
		return edt.getText().toString().trim();
	}

	public static boolean isStringNull(String str) {
        return str == null || "".equals(str);
    }

	public static boolean isListEmpty(List list) {
        return list == null || list.size() == 0;
    }

	/**
	 * 是否是邮箱格式
	 */
	public static boolean isEmail(String s) {
		Pattern pattern = Pattern.compile(
				"[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(s); 
		return matcher.matches();
	}

	/**
	 * 从bundle取字符串，照顾低版本没有默认值
	 */
	public static String getBundleString(Bundle bundle, String name,
			String defaultStr) {
		if (bundle != null) {
			String str = bundle.getString(name);
			if (isStringNull(str))
				return defaultStr;
			else
				return str;
		} else
			return defaultStr;
	}

	public static String getResString(Context context, int stringId) {
		return context.getResources().getString(stringId);
	}


	/**
	 * 判断list是否为空
	 */
	public static boolean isListNull(List list) {
        return list == null || list.size() == 0;
	}

	/**
	 * 加密账号 (4+"****")
	 * */
	public static String getEncryptAcNo(String acNo) {
		if (!isStringNull(acNo)) {
			if (acNo.length() > 4) {
				return acNo.substring(0, 4) + " **** "
						+ acNo.substring(acNo.length() - 4, acNo.length());
			} else {
				return acNo;
			}
		} else
			return "";
	}

	/**
	 * 加密身份证号码(2+"****")
	 * */
	public static String getEncryptIDCode(String IDCode) {

		if (isStringNull(IDCode))
			return "";
		if (IDCode.length() > 4) {
			return IDCode.substring(0, 2) + " **** "
					+ IDCode.substring(IDCode.length() - 2, IDCode.length());
		} else {
			return IDCode;
		}
	}

	/**
	 * 加密手机号 (3+"****")
	 * */
	public static String getEncryptPhoneNum(String phone) {

		if (phone.length() > 3) {
			return phone.substring(0, 3) + "****"
					+ phone.substring(phone.length() - 3, phone.length());
		} else {
			return phone;
		}
	}

	/**
	 * 加密用户名(2+"****")
	 * */
	public static String getEncryptUsername(String username) {

		if (username.length() >= 4) {
			return username.substring(0, 2)
					+ "****"
					+ username.substring(username.length() - 2,
							username.length());
		} else {
			return username;
		}
	}

	/**
	 * 姓名加密 张小三 ----> *三
	 */
	public static String getEncryName(String username) {
		if (username.length() >= 2) {
			return "*"
					+ username.substring(username.length() - 1,
							username.length());
		} else {
			return username;
		}
	}


	public static void setTranslucentStatus(Activity activity, boolean on) {
		Window win = activity.getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	public static void Hint(Context context, String s) {
		Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 比较两个double数的大小
	 * 
	 * @return true 表示double2比double1大
	 */
	public static boolean compare(String double1, String double2) {
		if(isStringNull(double1))
			double1 = "0";
		if(isStringNull(double2))
			double2 = "0";
        return new BigDecimal(double2.replace(",", "")).compareTo(new BigDecimal(
                double1.replace(",", ""))) > 0;
    }

	/**去除String里的 = 元*/
	public static String getAmount(TextView etAmount){
		String old = etAmount.getText().toString();
		if(TextUtils.isEmpty(old) ) {
			return "0.0";
		} else if(!TextUtils.isEmpty(old)  && old.contains("元")) {
			return old.replace("元", "");
		} else 
			return old;
	}
	
	/**加  = 元*/
	public static void format(EditText etAmount, String amount) {
		if(TextUtils.isEmpty(amount)) {
			etAmount.setText(""); 
		} else 
			etAmount.setText(amount + "元"); 
	}
	
	/**
	 * 使edittext只能输入两位小数
	 */
	public static void setAmountPoint(final EditText editText) {
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.toString().contains(".")) {
					if (s.length() - 1 - s.toString().indexOf(".") > 2) {
						s = s.toString().subSequence(0,
								s.toString().indexOf(".") + 3);
						editText.setText(s);
						editText.setSelection(s.length());
					}
				}
				if (s.toString().trim().substring(0).equals(".")) {
					s = "0" + s;
					editText.setText(s);
					editText.setSelection(2);
				}

				if (s.toString().startsWith("0")
						&& s.toString().trim().length() > 1) {
					if (!s.toString().substring(1, 2).equals(".")) {
						editText.setText(s.subSequence(0, 1));
						editText.setSelection(1);
						return;
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}
}